package com.globallogic.dailyplanner.ejb;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;

import com.globallogic.dailyplanner.dto.Mail;
import com.globallogic.dailyplanner.vo.JMSMessageVO;

@Stateless
public class MailServiceBean {
	@Resource(lookup="jms/DailyplannerFactory")
	private ConnectionFactory connectionFactory;
	
	public boolean sendMessage(String[] emails, Mail mail){
		boolean status = true;
		Connection connection = null;
		Session session = null;
		try {
			connection = connectionFactory.createConnection();
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			//TODO how to inject this part?
			InitialContext ctx = new InitialContext();    
            Queue queue = (Queue) ctx.lookup("jms/DailyPlannerQueue");
			MessageProducer producer = session.createProducer(queue);
			ObjectMessage message = session.createObjectMessage();
			
			JMSMessageVO jmsMessage = new JMSMessageVO();
			jmsMessage.setEmails(emails);
			jmsMessage.setMail(mail);
			
			message.setObject(jmsMessage);
			producer.send(message);
		} catch (Exception e) {
			status = false;
		}  finally{
			try {
				session.close();
				connection.close();
			} catch (JMSException e) {
			}
		}
		
		return status;
	}

}
